<template>
  <div>
    <breadcrumbs :data1="data1" :data2="data2"></breadcrumbs>
    <el-card>
      <el-row>
        <!-- 添加角色按钮 -->
        <el-col :span="4">
          <el-button type="primary" @click="addRoleBtn">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" stripe border>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-row
              class="borderbt"
              type="flex"
              align="middle"
              justify="start"
              v-for="item in props.row.children"
              :key="item.id"
            >
              <el-col :span="5" class="textright">
                <el-tag closable @close="updateTree(props.row,item.id)">{{ item.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row v-for="item2 in item.children" :key="item2.id">
                  <el-col :span="5">
                    <el-tag
                      closable
                      type="danger"
                      @close="updateTree(props.row,item2.id)"
                    >{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19" class="textleft">
                    <el-tag
                      closable
                      type="success"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="updateTree(props.row,item3.id)"
                      v-loading.fullscreen.lock="fullscreenLoading"
                    >{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="编号" width="60"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" prop="desc">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRoleBtn(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delRoleBtn(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="getPowerList(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色对话框 -->
      <el-dialog
        title="添加角色"
        :visible.sync="adddialogVisible"
        width="50%"
        :close-on-click-modal="false"
        @close="closeForm"
      >
        <el-form :model="addRoleInfo" :rules="addRoleRules" ref="addRoleForm" label-width="110px">
          <el-form-item label="角色名称:" prop="roleName">
            <el-input
              v-model="addRoleInfo.roleName"
              prefix-icon="el-icon-user"
              placeholder="请输入角色名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色描述:" prop="roleDesc">
            <el-input
              v-model="addRoleInfo.roleDesc"
              prefix-icon="el-icon-postcard"
              placeholder="请输入角色描述"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="adddialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑角色信息对话框 -->
      <el-dialog title="编辑角色信息" :visible.sync="editdialogVisible" width="50%">
        <el-form :model="editRoleInfo" ref="editUserForm" label-width="110px">
          <el-form-item label="角色名称:">
            <el-input
              v-model="editRoleInfo.roleName"
              prefix-icon="el-icon-user"
              placeholder="请输入角色名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色描述:">
            <el-input
              v-model="editRoleInfo.roleDesc"
              prefix-icon="el-icon-postcard"
              placeholder="请输入角色描述"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="editdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRole">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限对话框 -->
      <el-dialog title="权限管理" :visible.sync="powerdialogVisible" width="50%" @close="clearDefKeys">
        <span>
          <el-tree
            :data="powerList"
            show-checkbox
            :props="treeProps"
            :default-expand-all="true"
            node-key="id"
            :default-checked-keys="defkeys"
            ref="rightsRef"
          ></el-tree>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="powerdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
           
<script>
import breadcrumbs from '@/common/breadcrumbs'
import { setTimeout } from 'timers';
export default {
  data () {
    return {
      roleid: '',
      data1: '权限管理',
      data2: '角色列表',
      rolesList: [],
      powerdialogVisible: false,
      editdialogVisible: false,
      adddialogVisible: false,
      editRoleInfo: {
        roleName: '',
        roleDesc: ''
      },
      addRoleInfo: {
        roleName: '',
        roleDesc: ''
      },
      powerList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      defkeys: [],
      fullscreenLoading: false,
      addRoleRules: {
        roleName: [
          { required: true, message: '角色名称不能为空！', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '角色描述不能为空！', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ]
        }
    }
  },
  created () {
    this.getTree()
  },
  components: {
    breadcrumbs
  },
  methods: {
    async getTree () {
      const { data: res } = await this.$http.get('roles')
      // console.log(res);
      this.rolesList = res.data
    },
    async updateTree (id, rid) {

      const loading = this.$loading({
        lock: true,
        text: '拼命加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      const { data: res } = await this.$http.delete(`roles/${id.id}/rights/${rid}`)
      // console.log(res.data)
      setTimeout(() => {
        loading.close();
        if (res.meta.status === 200) {
          this.$message.success('删除成功~~')
        } else {
          this.$message.error(res.meta.msg)
        }
        id.children = res.data

      }, 1000);
    },
    async getPowerList (row) {
      this.roleid = row.id
      this.getdefkeys(row, this.defkeys)
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res);
      this.powerdialogVisible = true,
        this.powerList = res.data
    },
    getdefkeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getdefkeys(item, arr)
      })
    },
    clearDefKeys () {
      this.defkeys = []
    },
    async allotRights () {
      const data = [
        ...this.$refs.rightsRef.getCheckedKeys(),
        ...this.$refs.rightsRef.getHalfCheckedKeys(),
      ]
      const idStr = data.join()
      const { data: res } = await this.$http.post(`roles/${this.roleid}/rights`, {
        rids: idStr
      })
      if (res.meta.status === 200) {
        this.$message.success('权限更新成功~~')
        this.powerdialogVisible = false
        this.getTree()
      } else {
        this.$message.error(res.meta.msg)
      }
    },
    async editRoleBtn (roleid) {
      this.roleid = roleid
      const { data: res } = await this.$http.get(`roles/${roleid}`)
      this.editdialogVisible = true
      this.editRoleInfo = res.data
    },
    async editRole () {
      const { data: res } = await this.$http.put(`roles/${this.roleid}`, this.editRoleInfo)
      if (res.meta.status === 200) {
        this.$message.success('角色信息更新成功~~')
        this.editdialogVisible = false
        this.getTree()
      } else {
        this.$message.error(res.meta.msg)
      }
    },
    async delRoleBtn (roleid) {
      const { data: res } = await this.$http.get(`roles/${roleid}`)

      this.$confirm(`此操作将永久删除角色 <strong style="color:red;font-size:16px">'${res.data.roleName}'</strong> , 是否继续?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${roleid}`)
        if (res.meta.status === 200) {
          this.$message.success('角色删除成功~~')
          this.getTree()
        } else {
          this.$message.error(res.meta.msg)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作！'
        });
      });
    },
    addRoleBtn () {
      this.adddialogVisible = true
    },
    addRole () {
      this.$refs.addRoleForm.validate(async val =>{
        if(val){
          const {data:res} = await this.$http.post(`roles`,this.addRoleInfo)
          if (res.meta.status === 201) {
          this.$message.success('角色添加成功~~')
          this.adddialogVisible = false
          this.getTree()
        } else {
          this.$message.error(res.meta.msg)
        }
        }
      })
    },
    closeForm () {
      this.$refs.addRoleForm.resetFields()
    },

  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
.borderbt {
  border-bottom: 1px solid #ddd;
  // text-align: left!important;
}
.textright {
  text-align: right !important;
}
.textleft {
  text-align: left !important;
}
</style>